using EasyEditorGUI.Runtime;
using UnityEditor;
using UnityEngine;

namespace EasyEditorGUI.Editor
{
    [CustomPropertyDrawer(typeof(BitArrayAttribute))]
    public class BitArrayPropertyDrawer : PropertyDrawer
    {
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            EditorGUI.BeginProperty(position, label, property);
            var attr = attribute as BitArrayAttribute;
            bool hexValueAsLabel = fieldInfo.FieldType.IsArray;
            property.BitArrayGUI(position, attr.width, attr.supportSection ? GetBitWide() : attr.width,
                attr.order == BitOrder.RightToLeft, attr.showHexValue && !hexValueAsLabel, hexValueAsLabel);
            EditorGUI.EndProperty();
        }

        public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
        {
            var attr = attribute as BitArrayAttribute;
            return base.GetPropertyHeight(property, label) * GetSectionNum(attr);
        }

        byte GetBitWide()
        {
            var fieldType = fieldInfo.FieldType.IsArray
                ? fieldInfo.FieldType.GetElementType()
                : fieldInfo.FieldType;
            
            if (fieldType == typeof(int) || fieldType == typeof(uint))
            {
                return sizeof(int) * 8;
            }

            if (fieldType == typeof(long) || fieldType == typeof(ulong))
            {
                return sizeof(long) * 8;
            }

            if (fieldType == typeof(byte) || fieldType == typeof(char))
            {
                return sizeof(byte) * 8;
            }

            return 0;
        }

        int GetSectionNum(BitArrayAttribute attr)
        {
            if (!attr.supportSection)
            {
                return 1;
            }
            
            int bitWide = GetBitWide();
            return bitWide / attr.width + (bitWide % attr.width > 0 ? 1 : 0);
        }
    }
}